<template>
  <div class="admin-dashboard">
    <h1>管理员仪表板</h1>

    <!-- 今日统计 -->
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>今日统计</span>
        </div>
      </template>
      <div class="statistics">
        <div class="statistic-item">
          <h3>交易金额</h3>
          <p v-if="dailyStats.totalAmount">{{ dailyStats.totalAmount }} THB</p>
          <p v-else> 0 THB</p>
        </div>
        <div class="statistic-item">
          <h3>退款金额</h3>
          <p v-if="dailyStats.refundAmount">{{ dailyStats.refundAmount }} THB</p>
          <p v-else> 0 THB</p>
        </div>
        <div class="statistic-item">
          <h3>订单量</h3>
          <p v-if="dailyStats.orderCount">{{ dailyStats.orderCount }}</p>
          <p v-else>0</p>
        </div>
      </div>
    </el-card>

    <!-- 订单管理 -->
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>订单管理</span>
        </div>
      </template>
      <div class="order-management">
        <el-form :inline="true" :model="orderSearchForm" class="demo-form-inline">
          <el-form-item label="订单号">
            <el-input v-model="orderSearchForm.orderId" placeholder="订单号"></el-input>
          </el-form-item>
          <el-form-item label="状态">
            <el-select v-model="orderSearchForm.type" placeholder="状态" style="width: 120px" @change="searchOrders">
              <el-option label="全部" :value="-4"></el-option>
              <el-option label="待支付" :value="0"></el-option>
              <el-option label="待使用" :value="1"></el-option>
              <el-option label="已完成" :value="2"></el-option>
              <el-option label="已取消" :value="3"></el-option>
              <el-option label="退款审核中" :value="-1"></el-option>
              <el-option label="退款中" :value="-2"></el-option>
              <el-option label="已退款" :value="-3"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="searchOrders">查询</el-button>
          </el-form-item>
        </el-form>

        <el-table :data="orders" style="width: 100%">
          <el-table-column prop="orderId" label="订单号" width="180"></el-table-column>
          <el-table-column prop="payId" label="支付单号" width="180"></el-table-column>
          <el-table-column prop="createTime" label="创建时间" width="180"></el-table-column>
          <el-table-column prop="payPrice" label="支付金额" width="120"></el-table-column>
          <el-table-column prop="orderStatus" label="状态" width="120"></el-table-column>
          <el-table-column prop="orderStatusMsg" label="状态信息"></el-table-column>
        </el-table>

        <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            @total-change="handleTotalChange"
            :current-page="orderPagination.currentPage"
            :page-sizes="[10, 20, 50, 100]"
            :page-size="orderPagination.pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="orderPagination.total">
        </el-pagination>
      </div>
    </el-card>

    <!-- 退款审核 -->
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>退款审核 ({{ refundOrdersCount }} 个待审核)</span>
        </div>
      </template>
      <div class="refund-approval">
        <!-- 添加搜索表单 -->
        <el-form :inline="true" :model="refundSearchForm" class="demo-form-inline">
          <el-form-item label="订单号">
            <el-input v-model="refundSearchForm.orderId" placeholder="订单号"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="searchRefundOrders">查询</el-button>
          </el-form-item>
        </el-form>

        <el-table :data="refundOrders" style="width: 100%">
          <el-table-column prop="orderId" label="订单号" width="180"></el-table-column>
          <el-table-column prop="payId" label="支付单号" width="180"></el-table-column>
          <el-table-column prop="createTime" label="创建时间" width="180"></el-table-column>
          <el-table-column prop="payPrice" label="支付金额" width="120"></el-table-column>
          <el-table-column prop="refundReasonWap" label="退款原因"></el-table-column>
          <el-table-column prop="refundReasonWapExplain" label="退款描述"></el-table-column>
          <el-table-column label="操作" width="200">
            <template #default="scope">
              <el-button size="default" type="success" @click="approveRefund(scope.row)">批准</el-button>
              <el-button size="large" type="danger" @click="rejectRefund(scope.row)">拒绝</el-button>
            </template>
          </el-table-column>
        </el-table>

        <el-pagination
            @size-change="handleRefundSizeChange"
            @current-change="handleRefundCurrentChange"
            :current-page="refundPagination.currentPage"
            :page-sizes="[10, 20, 50, 100]"
            :page-size="refundPagination.pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="refundPagination.total">
        </el-pagination>
      </div>
    </el-card>

    <el-dialog v-model="rejectDialogVisible" title="拒绝退款">
      <el-form :model="rejectForm">
        <el-form-item label="拒绝理由" :label-width="formLabelWidth">
          <el-input v-model="rejectForm.reason" type="textarea" :rows="3"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
      <span class="dialog-footer">
        <el-button @click="rejectDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmReject">确认</el-button>
      </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { useStore } from 'vuex'
import { ElMessage, ElMessageBox } from 'element-plus'

const store = useStore()
// 订单搜索表单
const orderSearchForm = computed(() => store.getters['orders/getSearchForm'])
const refundSearchForm  = computed(() => store.getters['orders/getRefundSearchForm'])
// 订单列表
const orders = computed(() => store.getters['orders/getOrders'])
const currentOrder = ref(null)
const orderPagination = computed(() => ({
  currentPage: store.state.orders.orderPagination.currentPage,
  pageSize: store.state.orders.orderPagination.pageSize,
  total: store.state.orders.orderPagination.total
}))
const rejectDialogVisible = ref(false)
const rejectForm = ref({ reason: '' })
const formLabelWidth = '120px'

// 退款订单列表
const refundOrders = computed(() => store.getters['fetchRefundOrders/getRefundOrders'])
const refundPagination = computed(() => ({
  currentPage: store.state.orders.pagination.currentPage,
  pageSize: store.state.orders.pagination.pageSize,
  total: store.state.orders.pagination.total
}))
const refundOrdersCount = ref(0)

// 今日统计数据
const dailyStats = computed(() => store.getters['fetchDailyStats/getDailyStats'])

// 获取今日统计数据
const fetchDailyStats = async () => {
  try {
    await store.dispatch('fetchDailyStats/fetchDailyStats')
  } catch (error) {
    ElMessage.error('获取今日统计数据失败')
  }
}

// 搜索退款订单
const searchRefundOrders = async () => {
  try {
    await store.dispatch("fetchDailyStats/updateRefundSearchForm", refundSearchForm.value)
    await store.dispatch('fetchRefundOrders/fetchRefundOrders')
    refundOrdersCount.value = refundPagination.value.total
  } catch (error) {
    ElMessage.error('搜索退款订单失败')
  }
}

// 搜索订单
const searchOrders = async () => {
  try {
    await store.dispatch('orders/updateSearchForm', orderSearchForm.value)
    await store.dispatch('orders/orders')
  } catch (error) {
    ElMessage.error('搜索订单失败')
  }
}

// 获取退款订单
const fetchRefundOrders = async () => {
  try {
    await store.dispatch('fetchDailyStats/fetchRefundOrders', {
      type: refundSearchForm.value.type,
      page: refundPagination.value.page,
      limit: refundPagination.value.limit
    })
    refundOrdersCount.value = refundPagination.value.total
  } catch (error) {
    ElMessage.error('获取退款订单失败')
  }
}

// 处理订单分页变化
const handleSizeChange = async (val) => {
  try {
    await store.commit('orders/SET_ORDER_PAGE_SIZE', val)
    await store.dispatch('orders/orders')
  } catch (error) {
    ElMessage.error('更改页面大小失败')
  }
}

const handleCurrentChange = async (val) => {
  try {
    await store.commit('orders/SET_ORDER_CURRENT_PAGE', val )
    await store.dispatch('orders/orders')
  } catch (error) {
    ElMessage.error('更改页码失败')
  }
}

const handleTotalChange = async (val) => {
  try {
    await store.commit('orders/SET_ORDER_TOTAL', val )
    await store.dispatch('orders/orders')
  } catch (error) {
    ElMessage.error('更改数量失败')
  }
}

// 批准退款
const approveRefund = async (order) => {
  try {
    await ElMessageBox.confirm('确定要批准这笔退款吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    await store.dispatch('fetchRefundOrders/approveRefund', { id: order.id, orderId: order.orderId })
    ElMessage.success('退款已批准')
    fetchRefundOrders()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('批准退款失败')
    }
  }
}

// 拒绝退款
const rejectRefund = (order) => {
  currentOrder.value = order
  rejectDialogVisible.value = true
}

const confirmReject = async () => {
  if (!rejectForm.value.reason) {
    ElMessage.warning('请输入拒绝理由')
    return
  }

  try {
    await store.dispatch('fetchRefundOrders/rejectRefund', {
      id: currentOrder.value.id,
      orderId: currentOrder.value.orderId,
      reason: rejectForm.value.reason
    })
    ElMessage.success('退款已拒绝')
    rejectDialogVisible.value = false
    rejectForm.value.reason = ''
    fetchRefundOrders()
  } catch (error) {
    ElMessage.error('拒绝退款失败')
  }
}

// 处理退款订单分页变化
const handleRefundSizeChange = (val) => {
  store.commit('refundOrders/SET_PAGE_SIZE', val)
  fetchRefundOrders()
}

const handleRefundCurrentChange = (val) => {
  store.commit('refundOrders/SET_CURRENT_PAGE', val)
  fetchRefundOrders()
}

onMounted(() => {
  fetchDailyStats()
  searchOrders()
  fetchRefundOrders()
})
</script>

<style scoped>
.admin-dashboard {
  padding: 20px;
}

.box-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.statistics {
  display: flex;
  justify-content: space-around;
}

.statistic-item {
  text-align: center;
}

.order-management, .refund-approval {
  margin-top: 20px;
}

.el-pagination {
  margin-top: 20px;
  text-align: right;
}
</style>
